package com.mcxx.modules.system.service.write;

import cn.hutool.core.util.IdUtil;
import com.mcxx.common.exception.BizException;
import com.mcxx.modules.miniSalvation.order.entity.SalvtionBusinessEntity;
import com.mcxx.modules.system.dao.read.SalvationRuleReadDao;
import com.mcxx.modules.system.dao.write.SalvationRuleWriteDao;
import com.mcxx.modules.system.entity.SalvationRuleEntity;
import com.mcxx.util.Constant;
import com.mcxx.util.FailureCode;
import com.yinhai.ta404.core.security.vo.UserAccountVo;
import com.yinhai.ta404.core.transaction.annotation.TaTransactional;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;


@Service
@TaTransactional
public class SalvationRuleWriteService {

    @Resource
    private SalvationRuleWriteDao salvationRuleWriteDao;
    @Resource
    private SalvationRuleReadDao salvationRuleReadDao;


    
    public int insertIgnoreNull(SalvationRuleEntity salvationRule) {
    	return salvationRuleWriteDao.insertIgnoreNull(salvationRule);
    }

    
    public int update(SalvationRuleEntity salvationRule) {
    	return salvationRuleWriteDao.update(salvationRule);
    }

    
    public int updateIgnoreNull(SalvationRuleEntity salvationRule) {
    	return salvationRuleWriteDao.updateIgnoreNull(salvationRule);
    }

    
    public int delete(SalvationRuleEntity salvationRule) {
    	return salvationRuleWriteDao.delete(salvationRule);
    }

    
    public void saveRule(SalvationRuleEntity entity, UserAccountVo accountVo) {

        String businessType = entity.getBusinessType();

        String ruleType = entity.getRuleType();
        if(StringUtils.isNotEmpty(businessType)
                && (Constant.BusinessCode.TEKUN.equals(businessType) || Constant.BusinessCode.LINSHI.equals(businessType))
                && StringUtils.isNotEmpty(ruleType)
                && (Constant.SalvationRuleType.BASIC.equals(ruleType) || Constant.SalvationRuleType.EXTENSION.equals(ruleType))
        ){

            entity.setRuleType(Constant.SalvationRuleType.GENERAL);
            List<SalvationRuleEntity> list = salvationRuleReadDao.querySalvationRuleList(entity);
            if(null != list && list.size() > 0){
                throw new BizException(FailureCode.ERR_50004);
            }
        }


        entity.setId(IdUtil.simpleUUID());
        entity.setTaOrgId(accountVo.getOrgId());
        entity.setBusinessType(entity.getBusinessType());
        entity.setStatus(Constant.SalvationRuleState.DISABLED);
        entity.setCreateTime(new Date());
        entity.setCreateBy(accountVo.getUserId());

        insertIgnoreNull(entity);
    }
}
